package org.ccay.web.support.internal.impl;

import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.util.FileUtil;
import org.ccay.core.util.StringUtil;
import org.ccay.hypertext.StaticResource;
import org.ccay.hypertext.service.IStaticResourceService;
import org.ccay.registry.util.RegistryQueryUtil;
import org.ccay.web.support.WebRequestVO;
import org.ccay.web.support.filter.ResponseUtil;
import org.ccay.web.support.internal.IResourceHandler;


@Named("hypertextResourceHandler")
public class HypertextResourceHandler implements IResourceHandler{
	
	private static final ILogger logger = CcayLoggerFactory.getLogger(HypertextResourceHandler.class); 
	
	private static final Set<String> originalAllowSuffix;
	
	static{
		originalAllowSuffix = new HashSet<String>();
		originalAllowSuffix.add("html");
		originalAllowSuffix.add("css");
		originalAllowSuffix.add("js");
	}
	
	@Inject
	private IStaticResourceService staticResource;
	

	/**
	 * 是否需要从Html区装载
	 * @param webRequest
	 * @return
	 */
	private boolean needLoadHtml(WebRequestVO webRequest) {	
		boolean support = RegistryQueryUtil.getBooleanValue("Ccay.GlobalParamters.LoadResourceFromHypertext");
		if(!support){
			return false;
		}
		
		String suffix = FileUtil.getExtension(webRequest.getShortUri());
		if(originalAllowSuffix.contains(suffix)){
			return true;
		}
		String addSuffix = RegistryQueryUtil.getValue("Ccay.GlobalParamters.AdditionalSuffixLoadFromHypertext");
		if(!StringUtil.isNullOrEmpty(addSuffix)){
			String[] suffixs = addSuffix.split(",");
			for(String addsuf : suffixs){
				if(addsuf.equals(suffix)){
					return true;
				}
			}
		}
		return false;
	}
	
	@Override
	public void sendResourceToResponse(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
			WebRequestVO webRequest) throws IOException {
		//尝试从富文本区加载资源
		if(!needLoadHtml(webRequest)) {
			return;
		}
		
		// 处理html、js、css
		String shortUri= webRequest.getShortUri();
		
		
		StaticResource hyperText = staticResource.findByUrL(shortUri.substring(1));		
		if(hyperText == null){
			return;
		}
		 
		long serverModifiedTime = getDate(hyperText.getLastUpdateDate());
		
		if(ResponseUtil.process304(httpResponse, webRequest, serverModifiedTime)){
			webRequest.setHandled(true);
			return;
		}
		
		logger.debug("Resource found in html area: {0}. It will be used instead of the resource in the EAR." , shortUri);
		 		
		httpResponse.getWriter().write(hyperText.getContent());		
		
		webRequest.setHandled(true);
	}

	public void clearResourceCache() {
		
	}
	
	protected Long getDate(Date time){
		if(null == time) {
			return System.currentTimeMillis();
		}
		return time.getTime();
	}
	
}
